var express = require('express');
var router = express.Router();
let svg = require('svg-captcha');


let path = require('path');
let fs = require('fs');

/* get渲染页面 */
router.get('/register', function (req, res, next) {
  res.render('register')
});


// 验证码
router.get('/code', function (req, res) {
  let captcha = svg.create({
    color: true,
    background: '#333'
  })

  req.session.yzm = captcha.text;
  res.type('svg');
  res.send(captcha.data)
})

// post
router.post('/register', function (req, res, next) {
  //获取前端传递过来的参数
  let { username, password, password2, yzm } = req.body;

  // 判断内容是否为空
  if (!username || !password || !password2 || !yzm) {
    next('请输入有效的内容!')
    return;
  }

  //获取persons.json里面的数据
  let data = JSON.parse(fs.readFileSync(path.join(__dirname, '../persons.json')));

  //判断用户是否存在,如果存在提示用户名已存在, 否则注册成功
  let s = data.find(item => username == item.username);
  if (s) {
    next('用户名已存在');
    return;
  }

  // 判断两次密码是否一致
  if (password != password2) {
    next('两次密码不一致,请重新输入!!');
    return;
  }

  // 判断验证码是否正确, 不区分大小写
  if (yzm.toLowerCase() != req.session.yzm.toLowerCase()) {
    next('验证码不正确,请重新输入!!')
    return;
  }

  data.push({ username, password, yzm });
  fs.writeFileSync('./persons.json', JSON.stringify(data))
  res.render('aa', { exactness: '注册成功' })

});

module.exports = router;
